import Mocha from '../../modules/mocha.js';
// import RTLog from '../../modules/rt_log.js';
const { throttle } = require('../../modules/function_throttle');
const app = getApp();

Page({
    data: {
        radioItems: [
            { name: '功能异常', value: '功能异常', checked: 'true' },
            { name: '投诉举报', value: '投诉举报' },
            { name: '优化建议', value: '优化建议' }
        ],
        detailImgList: [],
        productInfo: {},
        formData: {},
        customErrorPopup: false,
        errContext: '',
    },
    onLoad() {
        this.mochaGetConfig();
    },
    mochaGetConfig() {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        Mocha.getConfig()
            .then((cfg) => {
                wx.hideLoading();
                this.setData({
                    productInfo: {
                        ...(cfg || []),
                        feedback_tip_img: cfg?.feedback_tip_img
                    }
                });
            })
            .catch(() => {
                wx.hideLoading();
            });
    },
    formSubmit: throttle(function (e) {
        let { radio, textarea } = e.detail.value;
        textarea = textarea.trim();
        this.setData({
            formData: {
                type: radio,
                content: this.utf16toEntities(textarea)
            }
        });
        if (!textarea.trim()) {
            wx.showModal({
                title: '温馨提示',
                content: '请先填写您遇到的问题后再提交哟！',
                showCancel: false,
                confirmText: '好哒'
            });
        } else {
            if (textarea.trim().toLowerCase() == 'see link') {
                wx.redirectTo({
                    url: '/packageA/pages/linktest/linktest'
                });
            } else if (textarea.trim().toLowerCase() == 'delete') {
                wx.redirectTo({
                    url: '/pages/follow/follow'
                });
            } else if (textarea.trim().toLowerCase() == 'console') {
                wx.redirectTo({
                    url: '/packageA/pages/feedback_admin/feedback_admin'
                });
            } else {
                getApp().mox.stat({ key: '点击反馈提交按钮' });
                this.addFeedbackContent();
                // let userInfo = wx.getStorageSync('__session__');
                // let newUserInfo = userInfo ? JSON.parse(userInfo) : getApp().mox.user;
                // getApp().mox.stat({key: '点击反馈提交按钮----4'});
                // if (newUserInfo) {
                //     console.log(1111111,'---if');
                //     if (newUserInfo.openid && newUserInfo.unionid) {
                //         console.log(1111111,'---newUserInfo.openid && newUserInfo.unionid');
                //         this.addFeedbackContent();
                //     } else {
                //         getApp().mox.login({
                //             success: () => {
                //                 console.log(1111111,'---login success');
                //                 this.addFeedbackContent();
                //             },
                //             fail: (err) => {
                //                 console.log(1111111,'---login fail');
                //                 mox.stat({key:`feedback_mox_init fail:${
                //                     err.msg || err.errMsg || '未知错误'
                //                 }`});
                //             }
                //         });
                //     }
                // } else {
                //     console.log(1111111,'---else');
                // }
            }
        }
    }, 1500),
    addFeedbackContent() {
        wx.showLoading({
            title: '提交中',
            mask: true
        });
        const { type, content } = this.data.formData;
        const { unionid, openid } = getApp().mox.user;
        let userInfo = wx.getStorageSync('__session__');
        let newUserInfo = userInfo ? JSON.parse(userInfo) : getApp().mox.user;
        wx.request({
            url: 'https://api.scf.moapp.net.cn/release/mocha/add',
            method: 'POST',
            header: {
                'content-type': 'application/json',
                appid: 'wx999703fd265c7cb2',
                openid,
                unionid,
                'app-version': '1.1.1.0104'
            },
            data: {
                type,
                content,
                imgs: this.data.detailImgList || '',
                name: '阔爱大孔农',
                nickname: newUserInfo.nickName || '匿名用户',
                status: this.getStatus()
            },
            success: (res) => {
                wx.hideLoading();
                if (res.statusCode == 200) {
                    getApp().mox.stat({ key: '提交反馈与投诉成功' });
                } else {
                    getApp().mox.stat({ key: `提交反馈与投诉失败` });
                }
                wx.showToast({
                    title: `提交${res.statusCode == 200 ? '成功' : '失败'}`,
                    icon: `${res.statusCode == 200 ? 'success' : 'error'}`,
                    mask: true
                });
                setTimeout(() => {
                    wx.reLaunch({
                        url: '/pages/index/index'
                    });
                }, 1000);
            },
            fail: (err) => {
                getApp().mox.stat({
                    key: `提交反馈与投诉失败`
                });
                this.setData({
                    errContext: `提交失败`,
                    customErrorPopup: true
                });
                // wx.showToast({
                //     title: `提交失败`,
                //     icon: 'error',
                //     mask: true
                // });
                wx.hideLoading();
            }
        });
    },
    uploadImg() {
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                wx.showLoading({
                    title: '上传中',
                    mask: true
                });
                wx.uploadFile({
                    url: 'https://api.scf.moapp.net.cn/release/upload_cos?sync_verify=1',
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    formData: {
                        path: 'weapp/wx999703fd265c7cb2'
                    },
                    success: (res) => {
                        const pkg = JSON.parse(res.data);
                        if (pkg.code == 'SUCCESS') {
                            this.setData({
                                detailImgList: this.data.detailImgList.concat(pkg.data.url)
                            });
                        } else {
                            wx.showToast({
                                title: '上传出错',
                                icon: 'error',
                                mask: true
                            });
                        }
                    },
                    complete: () => {
                        wx.hideLoading();
                    }
                });
            }
        });
    },
    openServicePreview() {
        let { qy_qrcode } = this.data.productInfo;
        wx.previewImage({
            urls: [qy_qrcode],
            showmenu: true
        });
    },
    // 将emoji表情其转成 base64
    utf16toEntities(str) {
        var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
        str = str.replace(patt, function (char) {
            var H, L, code;
            if (char.length === 2) {
                H = char.charCodeAt(0); // 取出高位
                L = char.charCodeAt(1); // 取出低位
                code = (H - 0xd800) * 0x400 + 0x10000 + L - 0xdc00; // 转换算法
                return '&#' + code + ';';
            } else {
                return char;
            }
        });
        return str;
    },

    // 解码emoji表情
    uncodeUtf16(str) {
        var reg = /\&#.*?;/g;
        var result = str.replace(reg, function (char) {
            var H, L, code;
            if (char.length == 9) {
                code = parseInt(char.match(/[0-9]+/g));
                H = Math.floor((code - 0x10000) / 0x400) + 0xd800;
                L = ((code - 0x10000) % 0x400) + 0xdc00;
                return unescape('%u' + H.toString(16) + '%u' + L.toString(16));
            } else {
                return char;
            }
        });
        return result;
    },
    getStatus() {
        const { content } = this.data.formData;
        let regx = /^[A-Za-z0-9]+$/;
        if (content?.length === 8 && regx.test(content)) {
            return ~~true;
        } else {
            return ~~false;
        }
    }
});
